//
//  OSTools.m
//  Stock_Pro
//
//  Created by CH on 11-2-14.
//  Copyright 2011 gaotime. All rights reserved.
//

#import "OSTools.h"
#import "Tools.h"
#import<mach/mach_time.h>
#import "ZipArchive.h"
#import <UIKit/UIScreen.h>

@implementation OSTools

+(void) TextFieldChangeText:(UITextField *) textField withLimit:(int) aLen {
  
  NSString *pStr = textField.text;
  
  char *text =  [pStr UTF8String];
  
  if (strlen(text) > aLen - 1) {
    return;
  }
  
  char sBuf[256];
  char sTBuf[256];
  memset(sBuf, 0, sizeof(sBuf));
  memset(sTBuf, 0, sizeof(sTBuf));
  strcpy(sBuf, text);
  int nLen = strlen(sBuf);
  char c;
  
  TBOOL b = TRUE;
  for (int i=0; i<nLen; i++) {
    c=sBuf[i];
    if ((c & MASK3BYTES) == MASK3BYTES)
    {
      i+=2;
      if (b) {
        if (strlen(sTBuf)>1) {
          TBOOL bbb = FALSE;
          for (int j=i-2; j<nLen; j++) {
            char ccc = sBuf[j];
            if ((u_byte)ccc < MASKBYTE)
            {
              bbb = TRUE;
              break;
            }
            else if ((c & MASK3BYTES) == MASK3BYTES)
            {
              j+=2;
            }
            else if ((c & MASK2BYTES) == MASK2BYTES)
            {
              j+=1;
            }
            
          }
          if (bbb) {
            char cc = sTBuf[strlen(sTBuf)-1];
            memset(sTBuf, 0, sizeof(sTBuf));
            sTBuf[0]=cc;
          }
        }
        b = FALSE;
      }
    }
    // 110xxxxx 10xxxxxx
    else if ((c & MASK2BYTES) == MASK2BYTES)
    {
      i+=1;
    }
    // 0xxxxxxx
    else if ((u_byte)c < MASKBYTE)
    {
      if (
          (c>=0x30 && c<=0x39)//数字
          ||(c>='a' && c<='z')//小写
          ||(c>='A' && c<='Z')//大写
          || c=='*'
          || c=='.'
          )
      {
        sTBuf[strlen(sTBuf)]=c;
      }
      else if(c==' '){
        break;
      }
      
    }
    
  }
  
  if (!strestr(sBuf,sTBuf)) {
    textField.text = [NSString stringWithUTF8String:sTBuf];
  }
  else
  {
    if (strlen(sTBuf)>aLen && aLen > 0) {
      sTBuf[aLen]=0;
      textField.text = [NSString stringWithUTF8String:sTBuf];
    }
  }
}

+(CGSize) AppSize
{
//  return CGSizeMake(750, 1334);
  CGSize size = [[UIScreen mainScreen] bounds].size;
  return  size;
}

+(int) calcHeight:(CGFloat)aModu
{
  return [[UIScreen mainScreen] bounds].size.height * aModu;
}

+(int) calcWidth:(CGFloat)aModu
{
  return [[UIScreen mainScreen] bounds].size.width * aModu;
}

+(int) BigFontHeight
{
  return 25;
}

+(int) MidFontHeight
{
  return 18;
}

+(int)SmallFontHeight
{
  return 14;
}

+(int)LeastFontHeight
{
  return 12;
}

+(CGSize) calcStringSize:(NSString*)aStr withFontSize:(UIFont*)font withWidth:(int)aWidth
{
//  UIFont *font = [UIFont systemFontOfSize:aSize];
  CGSize sSize;
  if (aWidth == -1) {
    sSize = [aStr sizeWithFont:font constrainedToSize:CGSizeMake(MAXFLOAT, MAXFLOAT)];
  }else{
    sSize = [aStr sizeWithFont:font constrainedToSize:CGSizeMake(aWidth, MAXFLOAT)];
    
  }
  return sSize;
}

+(int) mxGetTickCount
{
  int timeTick;
  mach_timebase_info_data_t info;
  uint64_t machineTime;
  mach_timebase_info(&info);
  machineTime =mach_absolute_time();
  timeTick = machineTime * info.numer / info.denom /1000000LL;
  
  return timeTick;
}

//一、下载zip资源
+(NSString*)DownloadTextFile:(NSString*)fileUrl fileName:(NSString*)_fileName
{
  NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask,YES);//使用C函数NSSearchPathForDirectoriesInDomains来获得沙盒中目录的全路径。
  NSString *ourDocumentPath =[documentPaths objectAtIndex:0];
  NSString *sandboxPath = NSHomeDirectory();
  NSString *documentPath = [sandboxPath  stringByAppendingPathComponent:@"Documents"];//将Documents添加到sandbox路径上//TestDownImgZip.app
  NSString *FileName=[documentPath stringByAppendingPathComponent:_fileName];//fileName就是保存文件的文件名
  NSFileManager *fileManager = [NSFileManager defaultManager];
  // Copy the database sql file from the resourcepath to the documentpath
  if ([fileManager fileExistsAtPath:FileName]){
    return FileName;
  }else{
    NSURL *url = [NSURL URLWithString:fileUrl];
    NSData *data = [NSData dataWithContentsOfURL:url];
    [data writeToFile:FileName atomically:YES];//将NSData类型对象data写入文件，文件名为FileName
  }
  return FileName;
}

//2.解压zip包
+(void)OpenZip:(NSString*)zipPath  unzipto:(NSString*)_unzipto
{
  ZipArchive* zip = [[ZipArchive alloc] init];
  if( [zip UnzipOpenFile:zipPath] )
  {
    BOOL ret = [zip UnzipFileTo:_unzipto overWrite:YES];
    if( NO==ret )
    {
      NSLog(@"error");
    }
    [zip UnzipCloseFile];
  }
  [zip release];
}

/**
 @method 获取指定宽度情况ixa，字符串value的高度
 @param value 待计算的字符串
 @param fontSize 字体的大小
 @param andWidth 限制字符串显示区域的宽度
 @result float 返回的高度
 */
+(float)heightForString:(NSString *)value fontSize:(float)fontSize andWidth:(float)width
{
  CGSize sizeToFit = [value sizeWithFont:[UIFont systemFontOfSize:fontSize] constrainedToSize:CGSizeMake(width, CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap];//此处的换行类型（lineBreakMode）可根据自己的实际情况进行设置
  return sizeToFit.height;
}

+(BOOL)DownloadAndOpenZip:(NSString*)fileUrl fileName:(NSString*)_fileName unzipto:(NSString*)_unzipto{
  NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask,YES);//使用C函数NSSearchPathForDirectoriesInDomains来获得沙盒中目录的全路径。
//  NSString *ourDocumentPath =[documentPaths objectAtIndex:0];
  NSString *sandboxPath = NSHomeDirectory();
  NSString *documentPath = [sandboxPath  stringByAppendingPathComponent:@"Documents"];//将Documents添加到sandbox路径上//TestDownImgZip.app
//  NSString *documentPath = [[NSBundle mainBundle] resourcePath];
  NSString *FileName=[documentPath stringByAppendingPathComponent:_fileName];//fileName就是保存文件的文件名
//  NSFileManager *fileManager = [NSFileManager defaultManager];
  
// Copy the database sql file from the resourcepath to the documentpath
  NSURL *url = [NSURL URLWithString:fileUrl];
  NSData *data = [NSData dataWithContentsOfURL:url];
  [data writeToFile:FileName atomically:YES];//将NSData类型对象data写入文件，文件名为FileName
  
  NSString *ziptoFile = [documentPath stringByAppendingPathComponent:_unzipto];
  
  remove([ziptoFile UTF8String]);
  
  ZipArchive* zip = [[ZipArchive alloc] init];
  if([zip UnzipOpenFile:FileName])
  {
    BOOL ret = [zip UnzipFileTo:ziptoFile overWrite:YES];
    if( NO==ret ){
      NSLog(@"error");
      return FALSE;
    }
    [zip UnzipCloseFile];
  }
  [zip release];
  
  remove([FileName UTF8String]);
  return TRUE;
}

+(NSString*) base64Encode:(NSData *)data{
  static char base64EncodingTable[64] = {
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
    'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
    'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
    'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
  };
  int length = [data length];
  unsigned long ixtext, lentext;
  long ctremaining;
  unsigned char input[3], output[4];
  short i, charsonline = 0, ctcopy;
  const unsigned char *raw;
  NSMutableString *result;
  
  lentext = [data length];
  if (lentext < 1)
    return @"";
  result = [NSMutableString stringWithCapacity: lentext];
  raw = [data bytes];
  ixtext = 0;
  
  while (true) {
    ctremaining = lentext - ixtext;
    if (ctremaining <= 0)
      break;
    for (i = 0; i < 3; i++) {
      unsigned long ix = ixtext + i;
      if (ix < lentext)
        input[i] = raw[ix];
      else
        input[i] = 0;
    }
    output[0] = (input[0] & 0xFC) >> 2;
    output[1] = ((input[0] & 0x03) << 4) | ((input[1] & 0xF0) >> 4);
    output[2] = ((input[1] & 0x0F) << 2) | ((input[2] & 0xC0) >> 6);
    output[3] = input[2] & 0x3F;
    ctcopy = 4;
    switch (ctremaining) {
      case 1:
        ctcopy = 2;
        break;
      case 2:
        ctcopy = 3;
        break;
    }
    
    for (i = 0; i < ctcopy; i++)
      [result appendString: [NSString stringWithFormat: @"%c", base64EncodingTable[output[i]]]];
    
    for (i = ctcopy; i < 4; i++)
      [result appendString: @"="];
    
    ixtext += 3;
    charsonline += 4;
    
    if ((length > 0) && (charsonline >= length))
      charsonline = 0;
  }
  return result;
}
/*
+(NSString *)tradeRequest_Syn:(NSString *)requestJsonString{
  NSString *response = @"";
  NSData *reqData =[requestJsonString dataUsingEncoding:NSUTF8StringEncoding];
  
  NSMutableData *tempJsonData = [NSMutableData dataWithData:reqData];
  NSURL *url = [NSURL URLWithString:@"http://119.147.80.166:7721/tradeapi/"];
//  NSURL *url = [NSURL URLWithString:@"https://waptrade.essence.com.cn/tradeapi/"];
  ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
  [request addRequestHeader:@"Content-Type" value:@"application/json; charset=utf-8"];
  [request addRequestHeader:@"Accept" value:@"application/json"];
  
  [request setRequestMethod:@"POST"];
  [request setPostBody:tempJsonData];
  [request startSynchronous];
  NSError *error1 = [request error];
  if (!error1){
//    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
//    response = [[NSString alloc] initWithData:[request responseData] encoding:enc];
    
    NSData *jsondata = [request responseData];
    
    response = [[NSString alloc]initWithBytes:[jsondata bytes]length:[jsondata length]encoding:NSUTF8StringEncoding];
    
//    response = [request responseString];
    NSLog(@"Test：%@",response);
  }
  return response;
}

+(void)tradeRequest_Asy:(NSString *)requestJsonString withRequest:(ASIHTTPRequest **)request{
//  NSString *response = @"";
  NSData *reqData =[requestJsonString dataUsingEncoding:NSUTF8StringEncoding];
  
  NSMutableData *tempJsonData = [NSMutableData dataWithData:reqData];
  NSURL *url = [NSURL URLWithString:@"http://119.147.80.166:7721/tradeapi/"];
//    NSURL *url = [NSURL URLWithString:@"https://waptrade.essence.com.cn/tradeapi/"];
  *request = [ASIHTTPRequest requestWithURL:url];
  [*request addRequestHeader:@"Content-Type" value:@"application/json; charset=utf-8"];
  [*request addRequestHeader:@"Accept" value:@"application/json"];
  
  [*request setRequestMethod:@"POST"];
  [*request setPostBody:tempJsonData];
  [*request startAsynchronous];
//  // 网络请求成功
//  [request setCompletionBlock:^{
//    NSData *jsondata = [request responseData];
//    __block response = [[NSString alloc]initWithBytes:[jsondata bytes]length:[jsondata length]encoding:NSUTF8StringEncoding];
//    //    response = [request responseString];
//    NSLog(@"Test：%@",response);
//  }];
//  
//  // 网络请求失败
//  [request setFailedBlock:^{
//  }];
}

//构建多请求JSON数组
+(NSMutableString *)createJSONString:(NSMutableArray *)requestArray{
  //1. 初始化可变字符串，存放最终生成json字串
  NSMutableString *jsonString = [[NSMutableString alloc] initWithString:@"["];
  
  if (requestArray.count < 1) {
    return @"";
  }
  
  //2. 遍历数组，取出键值对并按json格式存放
  for (int i=0; i<requestArray.count; i++) {
    if ([NSJSONSerialization isValidJSONObject:requestArray[i]]) {
      NSError *error;
      NSString *strTemp = nil;
      NSData *jsonData = [NSJSONSerialization dataWithJSONObject:requestArray[i] options:NSJSONWritingPrettyPrinted error: &error];
//      if (!error) {
        strTemp = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        [jsonString appendString:strTemp];
        [jsonString appendString:@","];
//      }
    }
  }
  
  // 3. 获取末尾逗号所在位置
  NSUInteger location = [jsonString length]-1;
  
  NSRange range = NSMakeRange(location, 1);
  
  // 4. 将末尾逗号换成结束的]}
  [jsonString replaceCharactersInRange:range withString:@"]"];
  
  NSLog(@"jsonString = %@",jsonString);
  
  return jsonString;
}
*/
@end
